package com.example.treehole.ui.page.treehole

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.sp
import com.example.treehole.LocalPostListViewModel
import com.example.treehole.LocalUserViewModel
import com.example.treehole.ui.component.PostCard
import com.example.treehole.ui.component.RefreshBox
import com.example.treehole.ui.model.PostInfo

@Composable
fun PopularPage() {
    val userViewModel = LocalUserViewModel.current
    val userId by userViewModel.userId.collectAsState()
    val jwlToken by userViewModel.jwlToken.collectAsState()

    val postListViewModel = LocalPostListViewModel.current
    val postList by postListViewModel.popularPostList.collectAsState()
    val listState = postListViewModel.popularListState

    val isRefreshing = remember { mutableStateOf(false) }

    LaunchedEffect(listState) {
        if (postList.isEmpty()) {
            userId?.let {
                isRefreshing.value = true
                postListViewModel.refreshPopularPostList(jwlToken, it)
                isRefreshing.value = false
            }
        }
    }

    RefreshBox(
            isRefreshing = isRefreshing,
            onRefresh = { userId?.let { postListViewModel.refreshPopularPostList(jwlToken, it) } }
    ) {
        if (postList.isNotEmpty()) {
            LazyColumn(state = listState) {
                if (!isRefreshing.value) {
                    itemsIndexed(postList) { index, item: PostInfo ->
                        PostCard(post = item, isPopularCard = true, popularRank = index + 1)
                    }
                }
            }
        } else {
            Box(
                    modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()),
                    contentAlignment = Alignment.Center
            ) { Text(text = "好像出了一点点小错误...", fontSize = 24.sp, color = Color.White) }
        }
    }
}
